package io.xccit.hotelsystem.ui.mine;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.Navigation;

import io.xccit.hotelsystem.MainActivity;
import io.xccit.hotelsystem.R;
import io.xccit.hotelsystem.databinding.FragmentMineBinding;
import io.xccit.hotelsystem.ui.order.OrderFragment;
import io.xccit.hotelsystem.utils.AuthUtils;

/**
 * 我的Fragment
 */
public class MineFragment extends Fragment {

    private static final String TAG = "MineFragment:";
    private FragmentMineBinding binding;
    private MineViewModel mineViewModel;

    /**
     * 跳转到订单页
     */
    private void navigateToOrders() { 
         // 跳转到MainActivity并加载OrderFragment，同时定位到底部导航第2项
         Intent intent = new Intent(requireActivity(), MainActivity.class); 
         intent.putExtra("fragment_to_load", "OrderFragment");
         intent.putExtra("nav_position", 2); 
         startActivity(intent); 
     }

    /**
     * 添加登出按钮
     * @param root
     */
    private void addLogoutButton(View root) {
        root.findViewById(R.id.layout_logout).setOnClickListener(v -> {
            // 处理退出登录逻辑
            mineViewModel.logout();
            // 清除SharedPreferences中的用户数据
            SharedPreferences prefs = requireContext().getSharedPreferences(AuthUtils.PREF_NAME, Context.MODE_PRIVATE);
            prefs.edit().clear().apply();
            updateUI(false); // 更新UI为未登录状态
            // 跳转到登录页面，防止用户继续操作
            navigateToLogin();
        });
    }

    /**
     * 添加登录、注册按钮
     * @param root
     */
    private void addLoginRegisterButtons(View root) {
        root.findViewById(R.id.btn_login).setOnClickListener(v -> {
            // 跳转到登录页面
            navigateToLogin();
        });
        
        root.findViewById(R.id.btn_register).setOnClickListener(v -> {
            // 跳转到注册页面
            navigateToRegister();
        });
    }

    /**
     * 更新视图渲染
     * @param isLoggedIn
     */
    private void updateUI(boolean isLoggedIn) {
        if (binding != null) {
            if (isLoggedIn) {
                binding.layoutLoggedIn.setVisibility(View.VISIBLE);
                binding.layoutNotLoggedIn.setVisibility(View.GONE);
            } else {
                binding.layoutLoggedIn.setVisibility(View.GONE);
                binding.layoutNotLoggedIn.setVisibility(View.VISIBLE);
            }
        }
    }

    /**
     * 去登录
     */
    private void navigateToLogin() {
        AuthUtils.navigateToLogin(requireActivity());
    }

    /**
     * 去注册
     */
    private void navigateToRegister() {
        AuthUtils.navigateToRegister(requireActivity());
    }

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        mineViewModel =
                new ViewModelProvider(this).get(MineViewModel.class);

        binding = FragmentMineBinding.inflate(inflater, container, false);
        View root = binding.getRoot();

        // 检查登录状态
        boolean isLoggedIn = checkLoginStatus();
        Log.d(TAG, "onCreateView: isLoggedIn:" + isLoggedIn);
        
        // 更新UI状态
        updateUI(isLoggedIn);
        
        if (isLoggedIn) {
            // 已登录状态
            TextView tvUsername = root.findViewById(R.id.tv_username);
            // 从AuthUtils获取用户名
            SharedPreferences prefs = requireContext().getSharedPreferences(AuthUtils.PREF_NAME, Context.MODE_PRIVATE);
            String username = prefs.getString(AuthUtils.KEY_USERNAME, "");
            tvUsername.setText(username);
            
            // 设置订单点击事件
            root.findViewById(R.id.layout_orders).setOnClickListener(v -> {
                // 跳转到订单页面
                navigateToOrders();
            });
            
            // 添加退出登录按钮
            addLogoutButton(root);
        } else {
            // 未登录状态
            addLoginRegisterButtons(root);
        }
        
        return root;
    }

    /**
     * 判断是否登录
     * @return
     */
    private boolean checkLoginStatus() {
        return AuthUtils.isLoggedIn(requireContext());
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
}